/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.oauth.service.impl

import com.gitee.minimalismstyle.fresh.common.security.domain.FreshGrantedAuthority
import com.gitee.minimalismstyle.fresh.common.security.domain.FreshUserDetails
import com.gitee.minimalismstyle.fresh.oauth.service.FreshUserDetailsService
import com.gitee.minimalismstyle.fresh.sys.api.model.SysUserRoles
import com.gitee.minimalismstyle.fresh.sys.api.service.SysUserService
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Service

import java.util.HashSet


@Service("userDetailService")
class UserDetailServiceImpl(val sysUserService: SysUserService) : FreshUserDetailsService {

    override fun loadUserByUsername(username: String): UserDetails? {
        val userRoles = sysUserService.findUserRolesByUsername(username).get(emptySysUserRoles())
        return getAuthority(userRoles)
    }

    protected fun getAuthority(userRoles: SysUserRoles): UserDetails {
        val authorities = HashSet<FreshGrantedAuthority>()
        val roles = userRoles.roles
        if (!roles.isNullOrEmpty()) {
            for (role in roles) {
                val grantedAuthority = FreshGrantedAuthority(role.id!!, role.code!!)
                authorities.add(grantedAuthority)

            }
        }
        return FreshUserDetails(
                userRoles.id!!,
                userRoles.tenantId!!,
                userRoles.groupId!!,
                userRoles.username!!,
                userRoles.password!!,
                authorities
        )
    }

    override fun loadUserByPhone(phone: String): UserDetails? {
        val user = sysUserService.findUserRolesByUsername(phone).get(emptySysUserRoles())
        return getAuthority(user)
    }

    private fun emptySysUserRoles(): SysUserRoles {
        return SysUserRoles()
    }
}
